package com.example.zcapi;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ArrayAdapter;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.util.EthernetUtil;
import com.zcapi;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.media.AudioManager;


public class MainActivity extends AppCompatActivity implements OnTimeListener{

    private String TAG = "MainActivity";
    zcapi zcApi;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE" };
    private static final int REQUEST_CODE = 1024;
    private Context mContext;

    TextView messageTextView;
    boolean statusBarEnable=true;
    boolean gestureStatusBarEnable=true;
    boolean bwatchDogEnable=true;

    String shutDown;//=this.getString(R.string.shutDown);//
    String reboot;//=this.getString(R.string.reboot);//
    String factoryReset;//=this.getString(R.string.factoryReset);//
    String updateOta;//=this.getString(R.string.OTA);//
    String setStatusBar;//=this.getString(R.string.statusBar);//
    String setGestureStatusBar;//=this.getString(R.string.gestureBar);//
    String setPowetOnOffTime;//=this.getString(R.string.powerOnOff);//
    String getBuildModel;//=this.getString(R.string.buildModel);//
    String getBuildSerial;//=this.getString(R.string.buildSerial);
    String getEthMacAddress;//=this.getString(R.string.ethMac);//
    String getWifiMacAddress;//=this.getString(R.string.wifiMac);//
    String setLcdOnOff;//=this.getString(R.string.lcdOff);//
    String gpioControl;//=this.getString(R.string.gpioControl);//
    String execShellCmd;//=this.getString(R.string.shellCmd);//
    String setSystemTime;//=this.getString(R.string.systemTime);//
    String watchDogEnable;//=this.getString(R.string.watchEnable);//
    String screenshot;//=this.getString(R.string.screenShot);//
    String InstallApk;//=this.getString(R.string.installApk);//
    String InstallApkRoot;//=this.getString(R.string.rootInstallApk);//
    String HDMIControl;//=this.getString(R.string.hdmiOff);//
    String SettingEthernetStaticIP;//=this.getString(R.string.ethStaticIP);//
    String SettingEthernetDHCP;//=this.getString(R.string.ethDHCP);//
    String getZcapiVersion;
    String setWlanIpAddress;
    String openCloseEth;           
    String closeEth;   
    String openCloseWifi;  
    String closeWifi;
    String getZckjID;    
    String openCloseBluetooth;   
    String closeBluetooth;
    String setInstallApkControl;
    String setInstallApkDisable;    
    String setVolumeUp;  
    String setVolumeDown;      
    String silentUninstallApk;     
    
    zcApiReceiver mZcApiReceiver;

    EthernetUtil ethernetUtil;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext=this;
        shutDown=this.getString(R.string.shutDown);// 
        reboot=this.getString(R.string.reboot);// 
        factoryReset=this.getString(R.string.factoryReset);// 
        updateOta=this.getString(R.string.OTA);// 
        setStatusBar=this.getString(R.string.statusBar);// 
        setGestureStatusBar=this.getString(R.string.gestureBar);// 
        setPowetOnOffTime=this.getString(R.string.powerOnOff);// 
        getBuildModel=this.getString(R.string.buildModel);//
        getBuildSerial=this.getString(R.string.buildSerial);// 
        getEthMacAddress=this.getString(R.string.ethMac);// 
        getWifiMacAddress=this.getString(R.string.wifiMac);// 
        setLcdOnOff=this.getString(R.string.lcdOff);// 
        gpioControl=this.getString(R.string.gpioControl);// 
        execShellCmd=this.getString(R.string.shellCmd);// 
        setSystemTime=this.getString(R.string.systemTime);// 
        watchDogEnable=this.getString(R.string.watchEnable);// 
        screenshot=this.getString(R.string.screenShot);// 
        InstallApk=this.getString(R.string.installApk);// 
        InstallApkRoot=this.getString(R.string.rootInstallApk);//
        HDMIControl=this.getString(R.string.hdmiOff);// 
        SettingEthernetStaticIP=this.getString(R.string.ethStaticIP);// 
        SettingEthernetDHCP=this.getString(R.string.ethDHCP);//
        getZcapiVersion=this.getString(R.string.getZcapiVersion);//
        setWlanIpAddress=this.getString(R.string.setWlanIpAddress);//
        openCloseEth=this.getString(R.string.openCloseEth);//openCloseEth        
        closeEth=this.getString(R.string.closeEth);// 
        openCloseWifi=this.getString(R.string.openCloseWifi);//      
        closeWifi=this.getString(R.string.closeWifi);//  closeBluetooth       
        getZckjID=this.getString(R.string.getZckjID);//   
        openCloseBluetooth=this.getString(R.string.openCloseBluetooth);//openCloseBluetooth 
        closeBluetooth=this.getString(R.string.closeBluetooth);//  closeBluetoth                   
        setInstallApkControl=this.getString(R.string.setInstallApkControl);//         
        setInstallApkDisable=this.getString(R.string.setInstallApkDisable);//  setInstallApkDisable    
        setVolumeUp=this.getString(R.string.setVolumeUp);                      
        setVolumeDown=this.getString(R.string.setVolumeDown);         
        silentUninstallApk=this.getString(R.string.silentUninstallApk);      
        
//        requestPermission();//
//        verifyStoragePermissions(this);// 
//        mZcApiReceiver = new zcApiReceiver();
//        IntentFilter filter = getIntentFilter();
//        IntentFilter intentFilter = new IntentFilter("android.56iq.intent.action.setpoweronoff");
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            registerReceiver(mZcApiReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
//            registerReceiver(new MyReceiver(), intentFilter, RECEIVER_VISIBLE_TO_INSTANT_APPS);
//        }else {
//            registerReceiver(mZcApiReceiver, filter);
//            registerReceiver(new MyReceiver(), intentFilter);
//        }

        zcApi=new zcapi();
        zcApi.getContext(getApplicationContext());
        ethernetUtil = new EthernetUtil();
        initView();
		if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
			verifyStoragePermissions(this);
		}

        findViewById(R.id.messageTextView).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimeSettingDialog timePicker = new TimeSettingDialog(MainActivity.this,0);
                timePicker.setOnTimeListener(MainActivity.this);
                timePicker.show();
            }
        });

        findViewById(R.id.cancelMessageTextView).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimeSettingDialog timePicker = new TimeSettingDialog(MainActivity.this,1);
                timePicker.setOnTimeListener(MainActivity.this);
                timePicker.show();
            }
        });
    }

    private static IntentFilter getIntentFilter() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.zc.action.setOnOffTimeStatus");
        filter.addAction("com.zc.action.setEthStatus");  //
        filter.addAction("com.zc.action.setWlanConfigStatus");
        filter.addAction("com.zc.action.ethEnableStatus");
        filter.addAction("com.zc.action.wifiEnableStatus");
        filter.addAction("com.zc.action.bluetoothEnableStatus");
        filter.addAction("com.zc.action.silentUninstallStatus");
        return filter;
    }

    @Override
    public void powerChange(int[] onTime, int[] offTime) {
        LogUtils.d(TAG, "checkPowerOnOff powerChange " + GsonUtils.toJson(onTime));
        LogUtils.d(TAG, "checkPowerOnOff powerChange " + GsonUtils.toJson(offTime));
//        AppApiUtils.getInstance(this).setPowetOnOffTime(true,onTime,offTime)
        zcApi.setPowetOnOffTime(true,onTime,offTime);
        ToastUtils.showShort("开关机设置成功");
//        zcApi.shutDown();
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                zcApi.setPowetOnOffTime(false,onTime,offTime);
//            }
//        }, 2000);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, YourReceiver.class); // 你的接收器
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
// 设置开机时间
//        alarmManager.setExact(AlarmManager.RTC_WAKEUP, 1000 * 60, pendingIntent);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            alarmManager.setExact(AlarmManager.RTC_WAKEUP, 1000, pendingIntent);
//        }
//        alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pendingIntent);
//        alarmManager.set(AlarmManager.RTC_WAKEUP, 1000 * 120, pendingIntent);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, 1000, pendingIntent);
//        } else
            //AlarmManager.RTC_WAKEUP表示闹钟类型为RTC，即闹钟会唤醒系统；在6.0版本后，set方法在暗屏时不保证发送广播
//            alarmManager.set(AlarmManager.RTC_WAKEUP, 1000 * 60, pendingIntent);
// 设置关机时间

    }

    @Override
    public void cancelPowerChange(int[] onTime, int[] offTime) {
        LogUtils.d(TAG,"checkPowerOnOff canclepowerChange " + GsonUtils.toJson(onTime));
        LogUtils.d(TAG,"checkPowerOnOff canclepowerChange " + GsonUtils.toJson(offTime));
        zcApi.setPowetOnOffTime(false,onTime,offTime);
        ToastUtils.showShort("取消开关机设置成功");
    }

    @Override
    public void powerByChange(long onTime, long offTime) {

    }

    class zcApiReceiver extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {

            if ("com.zc.action.setOnOffTimeStatus".equals(intent.getAction())) {
                Log.i(TAG, "zcApiReceiver------" + intent.getAction());
                int status = intent.getIntExtra("status", -1);
                Log.i(TAG, "zcApiReceiver------status=" + status);
                if(status==0){
                	showMessage(mContext.getString(R.string.timing)+" set success");
                    ToastUtils.showShort("设置成功");
                }
                if(status==1){
                	showMessage(mContext.getString(R.string.timing)+" cancel success");
                    ToastUtils.showShort("取消成功");
                }   
                if(status==-1){
                	showMessage(mContext.getString(R.string.timing)+" set fail");
                    ToastUtils.showShort("设置失败");
                }
                if(status==-2){
                	showMessage(mContext.getString(R.string.timing)+" cancel fail");
                    ToastUtils.showShort("取消失败");
                }                                                
            }
            if ("com.zc.action.setEthStatus".equals(intent.getAction())) {
                Log.i("zcapi", "zcApiReceiver------" + intent.getAction());
                int status = intent.getIntExtra("status", 0);
                /*
                   status:
                          1  DHCP success
                          -1 DHCP fail
                          2  STATIC success
                          -2 STATIC fail
                */                   
                Log.i("zcapi", "zcApiReceiver------status=" + status);
                if(status==1){
                	 showMessage(mContext.getString(R.string.ethdhcpip)+" success");
                }
                if(status==-1){
                	 showMessage(mContext.getString(R.string.ethdhcpip)+" fail");
                }   
                if(status==2){
                	 showMessage(mContext.getString(R.string.ethstaticipinfo)+" success");
                }
                if(status==-2){
                	 showMessage(mContext.getString(R.string.ethstaticipinfo)+" fail");
                }                                                
            }
            
            if ("com.zc.action.setWlanConfigStatus".equals(intent.getAction())) {
                Log.i("zcapi", "zcApiReceiver------" + intent.getAction());
                int status = intent.getIntExtra("status", -1);
                /*
                   status:
                          0  success
                          -1 wifi no connect
                          -2 ip error
                          -3 fail
                */                   
                Log.i("zcapi", "zcApiReceiver------status=" + status);
                if(status==0){
                	 showMessage(mContext.getString(R.string.wifisetip)+" success");
                }
                if(status==-1){
                	 showMessage(mContext.getString(R.string.wifisetip)+" No connect");
                }   
                if(status==-2){
                	 showMessage(mContext.getString(R.string.wifisetip)+" ip error");
                }
                if(status==-3){
                	 showMessage(mContext.getString(R.string.wifisetip)+" fail");
                }                                                
            }
            
            if ("com.zc.action.ethEnableStatus".equals(intent.getAction())) {
                Log.i("zcapi", "zcApiReceiver------" + intent.getAction());
                int status = intent.getIntExtra("status", 0);
                /*
                   status:
                          1  open success
                          2  close success
                          -2 close fail
                          -1 open fail
                */                   
                Log.i("zcapi", "zcApiReceiver------status=" + status);
                if(status==1){
                	 showMessage(mContext.getString(R.string.ethOpen)+" success");
                }
                if(status==-1){
                	 showMessage(mContext.getString(R.string.ethOpen)+" fail");
                }   
                if(status==2){
                	 showMessage(mContext.getString(R.string.ethClose)+" success");
                }
                if(status==-2){
                	 showMessage(mContext.getString(R.string.ethClose)+" fail");
                }                                                
            } 
            if ("com.zc.action.wifiEnableStatus".equals(intent.getAction())) {
                Log.i("zcapi", "zcApiReceiver------" + intent.getAction());
                int status = intent.getIntExtra("status", 0);
                /*
                   status:
                          1  open success
                          2  close success
                          -2 close fail
                          -1 open fail
                */                   
                Log.i("zcapi", "zcApiReceiver------status=" + status);
                if(status==1){
                	 showMessage(mContext.getString(R.string.wifiOpen)+" success");
                }
                if(status==-1){
                	 showMessage(mContext.getString(R.string.wifiOpen)+" fail");
                }   
                if(status==2){
                	 showMessage(mContext.getString(R.string.wifiClose)+" success");
                }
                if(status==-2){
                	 showMessage(mContext.getString(R.string.wifiClose)+" fail");
                }                                                
            }
            
            if ("com.zc.action.bluetoothEnableStatus".equals(intent.getAction())) {
                Log.i("zcapi", "zcApiReceiver------" + intent.getAction());
                int status = intent.getIntExtra("status", 0);
                /*
                   status:
                          1  open success
                          2  close success                           
                          -1 no bluetooth
                */                     
                Log.i("zcapi", "zcApiReceiver------status=" + status);
                if(status==1){
                	 showMessage(mContext.getString(R.string.bluetoothOpen)+" success");
                }
                if(status==-1){
                	 showMessage("no bluetooth");
                }   
                if(status==2){
                	 showMessage(mContext.getString(R.string.bluetoothClose)+" success");
                }                                              
            }                                    
                                    
            if ("com.zc.action.silentUninstallStatus".equals(intent.getAction())) {
                Log.i("zcapi", "zcApiReceiver------" + intent.getAction());
                int status = intent.getIntExtra("status", 0);
  	              /*
  	                status 1 success
  	                status -1 fail
  	                status 0 name error or no APK
  	              */                    
                Log.i("zcapi", "zcApiReceiver------status=" + status);
                if(status==1){
                	 showMessage("Uninstall success");
                }
                if(status==-1){
                	 showMessage("Uninstall fail");
                }   
                if(status==0){
                	 showMessage(" no APK or name error");
                }                                              
            }                                              
                                    
        }

    }    

    private void initView(){
        messageTextView=(TextView)findViewById(R.id.messageTextView);
        ListView listView;
        listView=(ListView) findViewById(R.id.APIListView);
        final MyAdapter mAdapter;

        mAdapter=new MyAdapter(this,getFunctionName());
        listView.setAdapter(mAdapter);//show the list

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //Toast.makeText(MainActivity.this,String.valueOf(i)+":"+getFunctionName().get(i),Toast.LENGTH_SHORT).show();
                //the number of functionName is defined in getFunctionName()
                String function=getFunctionName().get(i);
                {
                    if(function.equals(shutDown)){//shutDown
                        //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                        showMessage(mContext.getString(R.string.shutting));
                        zcApi.shutDown();
                    }
                    else if(function.equals(reboot)){//reboot
                         showMessage(mContext.getString(R.string.rebootting));
                        zcApi.reboot();
                    }
                    else if(function.equals(factoryReset)){//factoryReset
                        showMessage(mContext.getString(R.string.factoryReseting));
                        zcApi.factoryReset();
                    }
                    else if(function.equals(updateOta)){//updateOta
                        showMessage(mContext.getString(R.string.update));
                        zcApi.updateOta();
                    }
                    else if(function.equals(setStatusBar)){//setStatusBar
                        //showMessage("状态栏:"+(statusBarEnable?"允许":"禁止"));
                         showMessage(mContext.getString(R.string.status)+(statusBarEnable? mContext.getString(R.string.ok):mContext.getString(R.string.no)));
                        zcApi.setStatusBar(statusBarEnable);
                        statusBarEnable=!statusBarEnable;
                    }
                    else if(function.equals(setGestureStatusBar)){//setGestureStatusBar
                        //showMessage("滑动呼出状态栏:"+(gestureStatusBarEnable?"允许":"禁止"));
                         showMessage(mContext.getString(R.string.gesture)+(gestureStatusBarEnable? mContext.getString(R.string.pass):mContext.getString(R.string.nopass)));
                        zcApi.setGestureStatusBar(gestureStatusBarEnable);
                        gestureStatusBarEnable=!gestureStatusBarEnable;
                    }

                    else if(function.equals(setPowetOnOffTime)){//setPowetOnOffTime
                       // showMessage("1 分钟内关ｿ,3 分钟内启ｿ);
//                       showMessage(mContext.getString(R.string.timing));
                        Calendar calendar = Calendar.getInstance();
                        //获取系统的日ｿ

                        int year = calendar.get(Calendar.YEAR);
                        int month = calendar.get(Calendar.MONTH)+1;
                        int day = calendar.get(Calendar.DAY_OF_MONTH);
                        int hour = calendar.get(Calendar.HOUR_OF_DAY);
                        int minute = calendar.get(Calendar.MINUTE);
                        boolean enable=true;//取消或者使能定时开关机
                        //当前1分钟后关机，3分钟后开ｿ
                        int []onTime={year,month,day,hour,minute+3};
                      int []offTime={year,month,day,hour,minute+1};
                        zcApi.setPowetOnOffTime(enable,onTime,offTime);
                    }
                    else if(function.equals(getBuildModel)){//getBuildModel
                        String model=zcApi.getBuildModel();
                        //showMessage("设备型号"+model);
                         showMessage(mContext.getString(R.string.buildmodelZc)+model);

                    }
                    else if(function.equals(getBuildSerial)){//getBuildSerial
//                        Toast.makeText(getApplicationContext(),mContext.getString(R.string.info328e),Toast.LENGTH_LONG).show();
                        String serial=zcApi.getBuildSerial();
                        //String serial = Build.getSerial();
                        //showMessage("设备序列ｿ"+serial);
                         showMessage(mContext.getString(R.string.buildserialZc)+serial);
                    }
                    else if(function.equals(getEthMacAddress)){//getEthMacAddress
                        String EthMacAddress;
                        String EthMacAddress_1;
                        EthMacAddress=zcApi.getEthMacAddress("eth0");
                        EthMacAddress_1=zcApi.getEthMacAddress("eth1");
//                        showMessage("以太网MAC地址ETH0:"+EthMacAddress+"  ETH1:"+EthMacAddress_1);
                        showMessage(mContext.getString(R.string.ethmacinfo)+"ETH0:"+EthMacAddress+"  ETH1:"+EthMacAddress_1);
                    }
                    else if(function.equals(getWifiMacAddress)){//getWifiMacAddress
                        String WifiMacAddress;
                        WifiMacAddress=zcApi.getWifiMacAddress();
//                        showMessage("wifi MAC地址:"+WifiMacAddress);
                        showMessage(mContext.getString(R.string.wifimacinfo)+WifiMacAddress);
                    }
                    else if(function.equals(setLcdOnOff)){//setLcdOnOff
                        //showMessage("背光1秒后关闭 2秒后开ｿ");
                         showMessage(mContext.getString(R.string.lcdinfo));
                        handler.postDelayed(CloseBackLightRunnable,1000);
                        handler.postDelayed(OpenBackLightRunnable,2000);
                        //zcApi.setLcdOnOff(false);
                    }
                    else if(function.equals(gpioControl)){//gpioControl
                        //goto the gpio ControlActivity,it is too complex
                        //Log.e("szl",getPropStr("ro.pinhe.board"));
                        if(getPropStr("ro.pinhe.board").equals("ZC-328E")){
                            //Toast.makeText(getApplicationContext(),"328E旧主板GPIO丝印 1234顺序反过来：4321",Toast.LENGTH_LONG).show();
                            Toast.makeText(getApplicationContext(),mContext.getString(R.string.info328e),Toast.LENGTH_LONG).show();
                        }
                        Intent intent = new Intent();
                        Bundle data = new Bundle();
                        data.putString("myinfo",getPropStr("ro.pinhe.board"));
                        intent.putExtra("data",data);        //发送选择到的主板名字到controlActivity
                        intent.setClass(MainActivity.this, ControlActivity.class);
                        startActivity(intent);
                    }
                    else if(function.equals(execShellCmd)){//execShellCmd
                        //create a file /sdcard/execShellCmd,we can see the file in /sdcard/
                        String cmd="touch /sdcard/execShellCmd";
                       // showMessage("sd卡根目录中创建了新文ｿ/sdcard/execShellCmd");
                        showMessage(mContext.getString(R.string.fileinfo));
                        zcApi.execShellCmd(cmd);

                    }
                    else if(function.equals(setSystemTime)){//setSystemTime
                        //year,month,day,hour,minute,the format must right!
                        Calendar calendar = Calendar.getInstance();
                        //获取系统的日ｿ

                        int year = calendar.get(Calendar.YEAR);
                        int month = calendar.get(Calendar.MONTH)+1;
                        int day = calendar.get(Calendar.DAY_OF_MONTH);
                        int hour = calendar.get(Calendar.HOUR_OF_DAY);
                        int minute = calendar.get(Calendar.MINUTE);
                        int second = calendar.get(Calendar.SECOND);
                        if(hour>=21){
                            hour=3-(24-hour);
                        } else{
                            hour=hour+3;
                        }
                        int time[]={year,month,day,hour,minute,second};                        
                        zcApi.setSystemTime(time);
                        //showMessage("设置系统时间:"+year+" "+month+" "+day+" "+hour+" "+minute+" "+second);
                         showMessage(mContext.getString(R.string.systemtimeinfo)+year+" "+month+" "+day+" "+hour+" "+minute+" "+second);
                    }
                    else if(function.equals(watchDogEnable)){//watchDogEnable
                        //showMessage("看门ｿ"+(bwatchDogEnable?"开ｿ:"关闭")+" 两分钟内不关闭看门狗或者不再次喂狗 系统将重ｿ);
                        showMessage(mContext.getString(R.string.watchdoginfo)+(bwatchDogEnable?mContext.getString(R.string.watchdogopen):mContext.getString(R.string.watchdogclose))+" "+mContext.getString(R.string.watchdogrebootinfo)) ;
                        zcApi.watchDogEnable(bwatchDogEnable);
                        bwatchDogEnable=!bwatchDogEnable;
                    }
                    else if(function.equals(screenshot)){//screenshot
                        String path="/sdcard";
                        String fileName="screenshot.png";

                        //showMessage("截屏成功!文件ｿ /sdcard/screenshot.png");
                        showMessage(mContext.getString(R.string.screenshotinfo)+"/sdcard/screenshot.png");
                        zcApi.screenshot(path,fileName);
                        //startActivity(new Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS));
                        //getpackageInfo();


                    }
                    else if(function.equals(InstallApk)){//InstallApk
                        //put the apk then install the apk in /sdcard/test.apk
                        boolean isFileExist = copyAssetsSingleFile("/sdcard","hello.apk");
                        if(isFileExist){
                            String path="/sdcard/hello.apk";
                            //showMessage("普通安装应ｿ);
                            showMessage(mContext.getString(R.string.installAPKinfo));
                            zcApi.InstallApk(path,false);
                        }else{
                            //showMessage("请给apk读写存储权限");
                             showMessage(mContext.getString(R.string.canwrite));
                        }

                    }else if(function.equals(InstallApkRoot)){//InstallApk
                        //put the apk then install the apk in /sdcard/test.apk
                        boolean isFileExist = copyAssetsSingleFile("/sdcard","hello.apk");
                        if(isFileExist){
                            String path="/sdcard/hello.apk";
                            //showMessage("root安装应用ｿ);
                            showMessage(mContext.getString(R.string.rootapk));
                            zcApi.InstallApk(path,true);
                        }else{
                            //showMessage("请给apk读写存储权限");
                             showMessage(mContext.getString(R.string.canwrite));
                        }
                    }else if(function.equals(HDMIControl)){//InstallApk
                        //showMessage("HDMI 1秒后关闭 2秒后开ｿ支持328,339,356Xｿ588)");
                         showMessage(mContext.getString(R.string.hdmictl)+"328,339,356X,3588");
                        handler.postDelayed(HDMIOffRunnable,1000);
                        handler.postDelayed(HDMIOnRunnable,2000);
                    }else if (function.equals(SettingEthernetStaticIP)){
                        //showMessage("开始设置以太网静态IP");
                        //showMessage(mContext.getString(R.string.ethstaticipinfo));
                        showDialog();
                    } else if (function.equals(SettingEthernetDHCP)){
                        //showMessage("设置为以太网动态IP");
                         //showMessage(mContext.getString(R.string.ethdhcpip));
                        showDialogDHCP();
                    } else if (function.equals(getZcapiVersion)){
                         showMessage(mContext.getString(R.string.zcapiVersion)+zcApi.getZcapiVersion());
                    }
                      else if (function.equals(setWlanIpAddress)){
                         //showMessage(mContext.getString(R.string.setWlanIpAddress)+zcApi.setWlanIpAddress());
                         showWlanDialog();
                    }
                      else if (function.equals(openCloseEth)){
                       String ifaceName="eth0";
                       boolean ethEnable =true;
                       zcApi.openCloseEth(ifaceName,ethEnable);
                    }
                      else if (function.equals(closeEth)){
                       String ifaceName="eth0";
                       boolean ethEnable =false;
                       zcApi.openCloseEth(ifaceName,ethEnable);
                    } 
                      else if (function.equals(openCloseWifi)){//
                       boolean wifiEnable =true;
                       zcApi.openCloseWifi(wifiEnable);
                    }                   
                      else if (function.equals(closeWifi)){//
                       boolean wifiEnable =false;
                       zcApi.openCloseWifi(wifiEnable);
                    }
                      else if (function.equals(openCloseBluetooth)){//
                       boolean bluetoothEnable =true;
                       zcApi.openCloseBluetooth(bluetoothEnable);
                    }    
                      else if (function.equals(closeBluetooth)){//
                       boolean bluetoothEnable =false;
                       zcApi.openCloseBluetooth(bluetoothEnable);
                    }   
                      else if (function.equals(setInstallApkControl)){//
                       zcApi.setInstallApkControl("1");
                        showMessage("Install Apk open");
                    }                                        
                      else if (function.equals(setInstallApkDisable)){//
                       zcApi.setInstallApkControl("0");
                        showMessage("Install Apk close");
                    }                                                            
                      else if (function.equals(getZckjID)){//
                      	 Log.i("zcapi", "zcApi.getZckjID()------" + zcApi.getZckjID());
                       showMessage(zcApi.getZckjID());
                    }   
                      else if (function.equals(setVolumeUp)){//
                        AudioManager mAudioManager = (AudioManager) getSystemService(mContext.AUDIO_SERVICE);
                       mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_RAISE,AudioManager.FLAG_SHOW_UI);
                    }       
                      else if (function.equals(setVolumeDown)){//
                        AudioManager mAudioManager = (AudioManager) getSystemService(mContext.AUDIO_SERVICE);
                       mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_LOWER,AudioManager.FLAG_SHOW_UI);
                    }                                                                                                                                                                                 
                      else if (function.equals(silentUninstallApk)){//
                         zcApi.silentUninstallApk("com.example.helloworld");
//                          showMessage("Uninstall..");
                    }                                                                                                                                                                                                                        
                }

            }
        });

    }

    private void setDHCP(){
        Intent intent = new Intent("wits.intent.action.setethernetdhcp");
        this.sendBroadcast(intent);
        System.out.println();

    }

    private void getpackageInfo() {
        PackageManager pm = new AppCompatActivity().getPackageManager();
        for (PackageInfo lp : pm.getInstalledPackages(0)) {
            if (((ApplicationInfo.FLAG_SYSTEM & lp.applicationInfo.flags)==0)
                    && ((ApplicationInfo.FLAG_UPDATED_SYSTEM_APP & lp.applicationInfo.flags) == 0)
            && ((ApplicationInfo.FLAG_STOPPED & lp.applicationInfo.flags) == 0)){
                Log.i("ProcessUtil", "packageName=" + lp.packageName
                        + "  processName=" + lp.applicationInfo.processName);
            }
        }
    }



    Runnable OpenBackLightRunnable=new Runnable() {
        @Override
        public void run() {
            zcApi.setLcdOnOff(true);
            //开启背光就这一条指ｿ
        }
    };

    Runnable CloseBackLightRunnable=new Runnable() {
        @Override
        public void run() {
            zcApi.setLcdOnOff(false);

            //关闭背光就这一条指ｿ
        }
    };

    Runnable HDMIOnRunnable=new Runnable() {
        @Override
        public void run() {
            zcApi.setLcdOnOff(true,-1);
            //打开hdmi
        }
    };

    Runnable HDMIOffRunnable=new Runnable() {
        @Override
        public void run() {
            zcApi.setLcdOnOff(false,-1);
            //关闭hdmi
        }
    };

    private Handler handler = new Handler();               //开启一个handler任务


    private String getPropStr(String key) {
        Class<?> mClassType = null;
        Method mGetMethod = null;
        String value = "";
        try {
            if (mClassType == null) {
                mClassType = Class.forName("android.os.SystemProperties");
                mGetMethod = mClassType.getDeclaredMethod("get", String.class);
                value = (String) mGetMethod.invoke(mClassType, key);
            }
        } catch (Exception e) {
            e.printStackTrace();
            value = "";
        }
        return value;
    }

    private boolean copyAssetsSingleFile(String outPath, String fileName) {
        File file = new File(outPath);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                Log.e("--Method--", "copyAssetsSingleFile: cannot create directory.");
                return false;
            }
        }
        try {
            InputStream inputStream = getAssets().open(fileName);
            File outFile = new File(file, fileName);
            FileOutputStream fileOutputStream = new FileOutputStream(outFile);
            // Transfer bytes from inputStream to fileOutputStream
            byte[] buffer = new byte[1024];
            int byteRead;
            while (-1 != (byteRead = inputStream.read(buffer))) {
                fileOutputStream.write(buffer, 0, byteRead);
            }
            inputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    private void showMessage(String message){
       // messageTextView.setText("提示信息:"+message);
       messageTextView.setText(mContext.getString(R.string.remindinfo)+message);
    }



    private  ArrayList<java.lang.String> getFunctionName(){
        ArrayList<String> functionNameList=new ArrayList<String>();
        functionNameList.add(shutDown);//
        functionNameList.add(reboot);
        functionNameList.add(factoryReset);
        functionNameList.add(updateOta);
        functionNameList.add(setStatusBar);
        functionNameList.add(setGestureStatusBar);//
        functionNameList.add(setPowetOnOffTime);
        functionNameList.add(getBuildModel);
        functionNameList.add(getBuildSerial);
        functionNameList.add(getEthMacAddress);
        functionNameList.add(getWifiMacAddress);//
        functionNameList.add(setLcdOnOff);
        functionNameList.add(gpioControl);
        functionNameList.add(execShellCmd);//
        functionNameList.add(setSystemTime);
        functionNameList.add(watchDogEnable);
        functionNameList.add(screenshot);
        functionNameList.add(InstallApk);
        functionNameList.add(InstallApkRoot);
        functionNameList.add(HDMIControl);
        functionNameList.add(SettingEthernetStaticIP);
        functionNameList.add(SettingEthernetDHCP);
        functionNameList.add(getZcapiVersion); //       
        functionNameList.add(setWlanIpAddress); //      
        functionNameList.add(openCloseEth); //openCloseEth     
        functionNameList.add(closeEth); //
        functionNameList.add(openCloseWifi); //   
        functionNameList.add(closeWifi); //   
        functionNameList.add(getZckjID); //  
        functionNameList.add(openCloseBluetooth); //          
        functionNameList.add(closeBluetooth); //       
//        functionNameList.add(setInstallApkControl); //                
//        functionNameList.add(setInstallApkDisable); //    
        functionNameList.add(setVolumeUp); //   
        functionNameList.add(setVolumeDown); //                                                    
        functionNameList.add(silentUninstallApk); //                                               
        return functionNameList;
    }

    private void dialog(){
        View view= LayoutInflater.from(this).inflate(R.layout.start_dialog,null,false);
        final AlertDialog dialog = new AlertDialog.Builder(this).setView(view).create();

        final Button shutdown = view.findViewById(R.id.shutdown);
        final Button reboot = view.findViewById(R.id.reboot);


    }

    boolean isUseStatic = true;
    private void showWlanDialog(){

        View view = LayoutInflater.from(this).inflate(R.layout.wlan_dialog_layout, null, false);
        final AlertDialog dialog=new AlertDialog.Builder(this).setView(view).create();

        final Spinner sp_usestatic = view.findViewById(R.id.sp_usestatic);
        sp_usestatic.setPrompt(mContext.getString(R.string.selectmode));//(R.string.selectmode);//R.string.selectmode mContext.getString(R.string.timing)
        List<String> stringList = new ArrayList<>();
        stringList.add(mContext.getString(R.string.staticmode));//(R.string.staticmode);
        stringList.add(mContext.getString(R.string.dhcpmode));//(R.string.dhcpmode);
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, stringList);
        sp_usestatic.setAdapter(arrayAdapter);
        final EditText EdIp = view.findViewById(R.id.Ed_ip);
        final EditText EdGateway = view.findViewById(R.id.Ed_gateway);
        final EditText EdNetMask = view.findViewById(R.id.Ed_netMask);
        final EditText EdDns1 = view.findViewById(R.id.Ed_dns1);
        final EditText EdDns2 = view.findViewById(R.id.Ed_dns2);
        Button BuCancel=view.findViewById(R.id.Bu_cancel);
        Button BuConnect=view.findViewById(R.id.Bu_connect);
        EdIp.setText("192.168.3.12");
        EdGateway.setText("192.168.3.1");
        EdNetMask.setText("255.255.255.0");
        EdDns1.setText("8.8.8.8");
        EdDns2.setText("8.8.4.4");
        sp_usestatic.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
               @Override
               public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                   if (!("DHCP".equals(stringList.get(position)))) {
                   	 Log.i("wifiipmode","Static=true");
                       isUseStatic = true;
                       EdIp.setEnabled(true);
                       EdGateway.setEnabled(true);
                       EdNetMask.setEnabled(true);
                       EdDns1.setEnabled(true);
                       EdDns2.setEnabled(true);
                   } else {
                   	 Log.i("wifiipmode","Static=false");
                       isUseStatic = false;
                       EdIp.setEnabled(false);
                       EdGateway.setEnabled(false);
                       EdNetMask.setEnabled(false);
                       EdDns1.setEnabled(false);
                       EdDns2.setEnabled(false);
                   }
               }

               @Override
               public void onNothingSelected(AdapterView<?> parent) {

               }
           });
        BuCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();//关闭对话ｿ
            }
        });
        BuConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String ipAddr=EdIp.getText().toString();
                String gateway=EdGateway.getText().toString();
                String netMask=EdNetMask.getText().toString();
                String dns1=EdDns1.getText().toString();
                String dns2=EdDns2.getText().toString();
                System.out.println("set IP"+ipAddr+"\n"+gateway+"\n"+netMask+"\n"+dns1+"\n"+dns2);
                Log.i("wifiipmode","set IP"+ipAddr+"\n"+gateway+"\n"+netMask+"\n"+dns1+"\n"+dns2);
                if (isUseStatic) {
                    zcApi.setWlanIpAddress(isUseStatic, ipAddr,gateway,netMask,dns1,dns2);
                } else {
                    zcApi.setWlanIpAddress(isUseStatic, null, null,null,null,null);
                }
                dialog.dismiss();//关闭对话ｿ
            }
        });
        dialog.show();
    }
    private void showDialog(){
        View view= LayoutInflater.from(this).inflate(R.layout.ethernet_dialog_layout,null,false);
        final AlertDialog dialog=new AlertDialog.Builder(this).setView(view).create();

        final EditText EdIp = view.findViewById(R.id.Ed_ip);
        final EditText EdGateway = view.findViewById(R.id.Ed_gateway);
        final EditText EdNetMask = view.findViewById(R.id.Ed_netMask);
        final EditText EdDns1 = view.findViewById(R.id.Ed_dns1);
        final EditText EdDns2 = view.findViewById(R.id.Ed_dns2);
        final EditText EdIfaceName = view.findViewById(R.id.IfaceName);        
        Button BuCancel=view.findViewById(R.id.Bu_cancel);
        Button BuConnect=view.findViewById(R.id.Bu_connect);
        //设定初始值（可在对话框中更改ｿ
        EdIp.setText("192.168.3.12");
        EdGateway.setText("192.168.3.1");
        EdNetMask.setText("255.255.255.0");
        EdDns1.setText("8.8.8.8");
        EdDns2.setText("8.8.4.4");
        EdIfaceName.setText("eth0");

        BuCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();//关闭对话ｿ
            }
        });
        BuConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String ipAddr=EdIp.getText().toString();
                String gateway=EdGateway.getText().toString();
                String netMask=EdNetMask.getText().toString();
                String dns1=EdDns1.getText().toString();
                String dns2=EdDns2.getText().toString();
                String ifaceName=EdIfaceName.getText().toString();
                System.out.println("设置的IP"+ipAddr+"\n"+gateway+"\n"+netMask+"\n"+dns1+"\n"+dns2);
                Log.i("hsf111","设置的IP"+ipAddr+"\n"+gateway+"\n"+netMask+"\n"+dns1+"\n"+dns2);
                Log.i("hsf111","ifaceName="+ifaceName);
                zcApi.SetStaticIP(ipAddr,gateway,netMask,dns1,dns2,ifaceName);
                dialog.dismiss();//关闭对话ｿ
            }
        });
        dialog.show();

    }

    private void showDialogDHCP(){
        View view= LayoutInflater.from(this).inflate(R.layout.dhcp_dialog_layout,null,false);
        final AlertDialog dialog=new AlertDialog.Builder(this).setView(view).create();

        final EditText EdIfaceName = view.findViewById(R.id.IfaceName);        
        Button BuCancel=view.findViewById(R.id.Bu_cancel);
        Button BuConnect=view.findViewById(R.id.Bu_connect);
        EdIfaceName.setText("eth0");

        BuCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();//关闭对话ｿ
            }
        });
        BuConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String ifaceName=EdIfaceName.getText().toString();
                Log.i("hsf111","ifaceName="+ifaceName);
                zcApi.setDHCP(ifaceName);
                dialog.dismiss();//关闭对话ｿ
            }
        });
        dialog.show();

    }    
//    public static void verifyStoragePermissions(Activity activity) {
//
//        try {
//            //检测是否有写的权限
//
//            int permission = ActivityCompat.checkSelfPermission(activity,
//                    "android.permission.WRITE_EXTERNAL_STORAGE");
////            int phonePermission=ActivityCompat.checkSelfPermission(activity,"android.permission.READ_PHONE_STATE");
//            if (permission != PackageManager.PERMISSION_GRANTED) {
//                // 没有写的权限，去申请写的权限，会弹出对话ｿ
//                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
//            }
////            if (phonePermission!=PackageManager.PERMISSION_GRANTED){
////                ActivityCompat.requestPermissions(activity, PERMISSIONS_PHONE,REQUEST_PHONE_STATE);
////            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    public static void verifyStoragePermissions(Activity activity) {

        try {
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
//    private void requestPermission() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
//            // 先判断有没有权限
//            if (Environment.isExternalStorageManager()) {
//                //writeFile();
//            } else {
//                //startActivityForResult(new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION), REQUEST_CODE);
//                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
//            }
//        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            // 先判断有没有权限
//            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
//                    ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
//                //writeFile();
//            } else {
//                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
//            }
//        } else {
//            //writeFile();
//        }
//    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        if (requestCode == REQUEST_CODE) {
//            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
//                    ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
//                //writeFile();
//            } else {
//                //ToastUtils.show("存储权限获取失败");
//            }
//        }
//    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == REQUEST_CODE && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
//            if (Environment.isExternalStorageManager()) {
//                //writeFile();
//            } else {
//                //ToastUtils.show("存储权限获取失败");
//            }
//        }
//    }



}